<template>
  <div class="container">
    <el-row>
      <el-col :span="20" align="left">
        <el-form :inline="true" :model="formInline" class="demo-form-inline form-height" @keyup.enter.native="search">
          <el-form-item :label="$t('m.strategy.batch')">
            <el-input maxlength="20" show-word-limit v-model="formInline.name" placeholder></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="search"
              v-if="hasPermission('search')"
            >{{$t('m.query')}}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" align="right">
        <el-button type="primary" @click="add" v-if="hasPermission('add')">{{$t('m.add')}}</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="table"
      stripe
      empty-text
      fits
      class="table-wrap single-select-table"
      :data="tableData"
      :row-style="tableRowStyle"
      :row-class-name="tableRowClassName"
      @row-click="rowClick"
      @selection-change="handleSingleSelectionChange"
    >
      <el-table-column align="center" type="index" :label="$t('m.index')" width="55"></el-table-column>
      <el-table-column
        align="center"
        prop="batchattribute"
        :label="$t('m.strategy.batch')+$t('m.name')"
      >
        <template slot-scope="scope">
          <template v-if="hasPermission('table-batchattribute')">
            <el-button @click.stop="open(scope.row)" type="text">{{scope.row.batchattribute}}</el-button>
          </template>
          <template v-else>{{scope.row.batchattribute}}</template>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="describe" :label="$t('m.strategy.describe')"></el-table-column>
      <el-table-column align="center" prop="state" :label="$t('m.state')">
        <template slot-scope="scope">{{scope.row.state?$t('m.started'):$t('m.stopped')}}</template>
      </el-table-column>
      <el-table-column align="center" prop="creator" :label="$t('m.creator')"></el-table-column>
      <el-table-column align="center" prop="createdate" :label="$t('m.createdate')"></el-table-column>
      <el-table-column width="180" align="center" :label="$t('m.operation')">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state&&hasPermission('table-edit')"
            @click.stop="edit(scope.row)"
            size="mini"
            type="primary"
          >{{$t('m.edit')}}</el-button>
          <el-button
            v-if="hasPermission('table-edit')"
            :type="scope.row.state?'primary':''"
            size="mini"
            @click.stop="changeState(scope.row.batchattributeid, (scope.row.state+1)%2)"
          >{{scope.row.state?$t('m.stop'):$t('m.start')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="sizes, prev, pager, next, jumper"
      :page-sizes="pageSizeList"
      :page-size="rowSize"
      :current-page="page"
      :total="totalRows"
      @current-change="currentChangeInitFn"
      @size-change="handleSizeChangeInitFn"
    ></el-pagination>
    <el-dialog
      :close-on-click-modal="false"
      width="1200px"
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="close"
    >
      <div v-loading="popLoading">
        <el-form :rules="ruleForm" ref="refForm" size="mini" :model="formData">
          <el-form-item
            :label="$t('m.strategy.batch')+$t('m.name')"
            :label-width="formLabelWidth"
            prop="batchattribute"
            align="left"
          >
            <el-input
              :disabled="isdisabled"
              size="mini"
              v-model="formData.batchattribute"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('m.strategy.type')"
            :label-width="formLabelWidth"
            prop="typeid"
            align="left"
            v-loading="treeLoading"
          >
            <div class="tree">
              <el-tree
                ref="tree"
                @check-change="getChecked"
                :data="protype"
                show-checkbox
                node-key="id"
                :props="defaultProps"
              ></el-tree>
            </div>
          </el-form-item>
          <el-form-item
            :label="$t('m.strategy.describe')"
            :label-width="formLabelWidth"
            prop="describe"
            align="left"
          >
            <el-input
              :disabled="isdisabled"
              type="textarea"
              size="mini"
              v-model="formData.describe"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-table :data="formData.batchattrrulelist" style="width: 100%;margin-bottom:30px;">
            <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
            <!-- <el-table-column :label="$t('m.strategy.enable')" width="120" align="center">
              <template slot-scope="scope">
                <el-form-item prop="'batchattrrulelist.'+scope.$index+'.checked'">
                  <el-checkbox @change="enable" v-model="scope.row.checked"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>-->
            <el-table-column :label="$t('m.strategy.enable')" width="120" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'batchattrrulelist.'+scope.$index+'.enable'">
                  <el-checkbox @change="enable" :disabled="isdisabled" v-model="scope.row.enable"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.strategy.label')" align="center">
              <template slot-scope="scope">
                <el-form-item prop="label">
                  <el-input :disabled="isdisabled" v-model="scope.row.label"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.strategy.shortname')" align="center">
              <template slot-scope="scope">
                <el-form-item prop="shortname">
                  <el-input :disabled="isdisabled" v-model="scope.row.shortname"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.strategy.display')" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'batchattrrulelist.'+scope.$index+'.display'">
                  <el-checkbox :disabled="isdisabled" v-model="scope.row.display"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.strategy.inputtype')" align="center">
              <template slot-scope="scope">
                <el-form-item prop="inputtype">
                  <el-select
                    :disabled="isdisabled"
                    v-model="scope.row.inputtype"
                    :placeholder="$t('m.choose')"
                  >
                    <el-option
                      v-for="item in inputtype"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address" :label="$t('m.strategy.format')" align="center">
              <template slot-scope="scope">
                <el-form-item prop="format">
                  <el-select
                    :disabled="isdisabled"
                    v-model="scope.row.format"
                    :placeholder="$t('m.choose')"
                  >
                    <el-option
                      v-for="item in format"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              :label="$t('m.strategy.attributeoptions')"
              align="center"
            >
              <template slot-scope="scope">
                <el-form-item prop="attributeoptions">
                  <el-input :disabled="isdisabled" v-model="scope.row.attributeoptions"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address" :label="$t('m.strategy.keyattributes')" align="center">
              <template slot-scope="scope">
                <el-form-item prop="keyattributes">
                  <el-checkbox :disabled="isdisabled" v-model="scope.row.keyattributes"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address" :label="$t('m.strategy.validation')" align="center">
              <template slot-scope="scope">
                <el-form-item prop="validation">
                  <el-checkbox :disabled="isdisabled" v-model="scope.row.validation"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div align="left" style="margin-bottom:50px;">
          <el-button
            v-if="btnControl==0||btnControl==2"
            size="mini"
            type="primary"
            @click="addLabel"
          >{{$t('m.add')+$t('m.strategy.label')}}</el-button>
        </div>
        <div class="btns">
          <el-button size="mini" @click="close">{{$t('m.cancel')}}</el-button>
          <el-button
            v-if="btnControl==0||btnControl==2"
            size="mini"
            type="primary"
            @click="save()"
          >{{$t('m.confirm')}}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '@/utils/common'
export default {
  data(){
    return {
      isdisabled:false,
      status_loading:false,
      dialogFormVisible:false,
      treeLoading:false,
      formData:{
        batchattribute:'',
        batchattributeid:null,
        checked:true,
        batchattrrulelist:[
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.sigin.productiondate'),
            ruleid:0,
            shortname:this.$t('m.sigin.productiondate'),
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.strategy.expiration'),
            ruleid:0,
            shortname:this.$t('m.strategy.expiration'),
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.otherstore.indate'),
            ruleid:0,
            shortname:this.$t('m.otherstore.indate'),
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.strategy.effective'),
            ruleid:0,
            shortname:this.$t('m.strategy.effective'),
            validation:false
          }
        ],
        describe:'',
        producttypelist:[
          {
            typeid:null,
            typename:''
          }
        ],
        state:1
      },
      tableData:[],
      formLabelWidth:'160px',
      formInline:{
        name:''
      },
      title:'',
      treeArr:[],
      popLoading:false,

      protype:[],
      defaultProps:{
        children:'childrens',
        label:'typename'
      },

      checkPush:0, //判断是不是可以添加label
      flag:0, //判断是不是可以设置tree的node
      btnControl:0 //0:添加1：查看2：编辑
    }
  },
  watch:{
    dialogFormVisible(){
      this.formData = {
        batchattribute:'',
        batchattributeid:null,
        checked:true,
        batchattrrulelist:[
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.sigin.productiondate'),
            ruleid:0,
            shortname:this.$t('m.sigin.productiondate'),
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.strategy.expiration'),
            ruleid:0,
            shortname:this.$t('m.strategy.expiration'),
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.otherstore.indate'),
            ruleid:0,
            shortname:this.$t('m.otherstore.indate'),
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:this.$t('m.strategy.effective'),
            ruleid:0,
            shortname:this.$t('m.strategy.effective'),
            validation:false
          }
        ],
        describe:'',
        producttypelist:[
          {
            typeid:null,
            typename:''
          }
        ],
        state:1
      }
    }
  },
  computed:{
    ruleForm(){
      this.$nextTick(() => {
        this.$refs.refForm.clearValidate()
      })
      return {
        batchattribute:[
          {
            required:true,
            message:this.$t('m.enter') +
              this.$t('m.strategy.batch') +
              this.$t('m.name'),
            trigger:'blur'
          }
        ]
      }
    },
    format(){
      return [
        { label:this.$t('m.strategy.string'), value:1 },
        { label:this.$t('m.strategy.number'), value:2 },
        { label:this.$t('m.strategy.date'), value:3 },
        { label:this.$t('m.strategy.time'), value:4 }
      ]
    },
    inputtype(){
      return [
        { label:this.$t('m.strategy.inputtype1'), value:1 },
        { label:this.$t('m.strategy.inputtype2'), value:2 },
        { label:this.$t('m.strategy.inputtype3'), value:3 },
        { label:this.$t('m.strategy.inputtype4'), value:0 }
      ]
    }
  },
  methods:{
    init(){
      this.status_loading = true
      this.$axios({
        method:'get',
        url:'/batchattr/page',
        params:{
          page:this.page,
          rows:this.rowSize,
          name:this.formInline.name
        }
      }).then(({data})=> {
        for (let i = 0; i < data.records.length; i++){
          data.records[
            i
          ].createdate = common.timestampToTime(
            data.records[i].createdate
          )
        }

        this.tableData = data.records
        this.totalRows = data.total
        this.status_loading = false
      })
    },
    search(){
      this.page = 1
      this.init()
    },
    add(){
      this.isdisabled = false
      this.btnControl = 0;
      (this.title = this.$t('m.add') + this.$t('m.strategy.batch')),
      (this.dialogFormVisible = true)
    },
    open(row){
      this.isdisabled = true
      this.btnControl = 1
      this.title = this.$t('m.strategy.batch')
      let that = this
      if (that.flag === 0){
        that.$message(that.$t('m.strategy.loading'))
      } else {
        that.getInfoById(row.batchattributeid)
      }
    },
    edit(row){
      this.isdisabled = false
      this.btnControl = 2
      this.title = this.$t('m.edit') + this.$t('m.strategy.batch')
      let that = this
      if (that.flag === 0){
        that.$message(that.$t('m.strategy.loading'))
      } else {
        that.getInfoById(row.batchattributeid)
      }
    },
    close(){
      this.formData = {
        batchattribute:'',
        batchattributeid:null,
        checked:true,
        batchattrrulelist:[
          {
            // checked: true,
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:'生产日期',
            ruleid:0,
            shortname:'生产日期',
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:'失效日期',
            ruleid:0,
            shortname:'失效日期',
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:'入库日期',
            ruleid:0,
            shortname:'入库日期',
            validation:false
          },
          {
            attributeoptions:'',
            batchattributeid:0,
            display:false,
            enable:false,
            format:3,
            inputtype:null,
            keyattributes:false,
            label:'有效日期',
            ruleid:0,
            shortname:'有效日期',
            validation:false
          }
        ],
        describe:'',
        producttypelist:[
          {
            typeid:null,
            typename:''
          }
        ],
        state:1
      }
      this.$refs.tree.setCheckedNodes([])
      this.dialogFormVisible = false
    },
    getChecked(){
      let that = this
      that.formData.producttypelist = []
      that.treeArr = that.$refs.tree.getCheckedNodes()
      that.treeArr.forEach((item) => {
        that.formData.producttypelist.push({
          typename:item.typename,
          typeid:item.id
        })
      })
    },
    checkLable(){
      let that = this
      that.checkPush = 1
      for (let i = 0; i < that.formData.batchattrrulelist.length; i++){
        that.formData.batchattrrulelist[i].value = 1
        let obj = that.formData.batchattrrulelist[i]
        for (let key in obj){
          if (obj[key] === null || obj[key] === ''){
            that.checkPush = 0
            return that.$message({
              showClose:true,
              message:that.$t('m.strategy.isadd'),
              type:'error',
              duration:1500
            })
          }
        }
      }
    },
    addLabel(){
      let that = this
      that.checkLable()
      if (that.checkPush === 1){
        that.formData.batchattrrulelist.push({
          attributeoptions:'',
          batchattributeid:0,
          display:0,
          enable:[],
          format:null,
          inputtype:null,
          keyattributes:0,
          label:'',
          ruleid:0,
          shortname:'',
          validation:0
        })
      }
    },
    save(){
      let that = this
      that.$refs['refForm'].validate(valid => {
        if (valid){
          if (that.treeArr.length < 1){
            that.$message({
              showClose:true,
              message:that.$t('m.choose') + that.$t('m.type'),
              type:'error',
              duration:1500
            })
          } else {
            that.checkLable()
            if (that.checkPush === 1){
              that.formData.batchattrrulelist.forEach(item => {
                if (item.display === true){
                  item.display = 1
                } else {
                  item.display = 0
                }
                if (item.enable === true){
                  item.enable = 1
                } else {
                  item.enable = 0
                }
                if (item.keyattributes === true){
                  item.keyattributes = 1
                } else {
                  item.keyattributes = 0
                }
                if (item.validation === true){
                  item.validation = 1
                } else {
                  item.validation = 0
                }
              })
              let objStr = JSON.stringify({ ...that.formData })
              let url = ''
              let message = ''
              if (that.btnControl === 0){
                url = '/batchattr/add'
                message = that.$t('m.success')
              }
              if (that.btnControl === 2){
                url = '/batchattr/update'
                message = that.$t('m.editSuccess')
              }
              that
                .$axios({
                  method:'post',
                  url,
                  data:objStr
                })

                .then(()=> {
                  that.$message({
                    showClose:true,
                    message:message,
                    type:'success',
                    duration:1500
                  })
                  that.init(1, 10)
                  that.dialogFormVisible = false
                })
            }
          }
        }
      })
    },
    getProtypeTree(){
      this.treeLoading = true
      this.flag = 0
      this.$axios({
        method:'get',
        url:'/protype/tree'
      }).then(({data})=> {
        this.protype = data
        this.flag = 1
        this.treeLoading = false
      })
    },
    getInfoById(id){
      let that = this
      this.clickId = id
      this.popLoading = true
      this.dialogFormVisible = true
      this.$axios({
        method:'get',
        url:`/batchattr/${id}`
      }).then(({data})=> {
        this.formData = data
        let list = this.formData.batchattrrulelist
        list.forEach(v => {
          if (v.enable === 1) v.enable = true
          if (v.enable === 0 || !v.enable) v.enable = false
          if (v.display === 1) v.display = true
          if (v.display === 0 || !v.display) v.display = false
          if (v.validation === 1) v.validation = true
          if (v.validation === 0 || !v.validation) v.validation = false
          if (v.keyattributes === 1) v.keyattributes = true
          if (v.keyattributes === 0 || !v.keyattributes)
            v.keyattributes = false
        })
        this.checkedArr = []
        this.formData.producttypelist.forEach(item => {
          this.checkedArr.push({
            id:item.typeid,
            label:item.typename
          })
        })
        if (this.flag === 1){
          this.$refs.tree.setCheckedNodes(this.checkedArr)
        }
        this.popLoading = false
      })
    },
    //node（item）为第一层节点
    getTreeNode(node){
      if (node){
        node.disabled = true
      }
    },
    changeState(id, state){
      this.$axios({
        method:'put',
        url:`/batchattr/${id}/state`,
        params:{ state }
      }).then(()=> {
        this.page = 1
        this.init()
      })
    }
  },
  created(){
    this.init()
    this.getProtypeTree()
  },
  beforeRouteLeave(to, form, next){
    this.dialogFormVisible=false
    next()
  }
}
</script>
<style lang="scss" scoped>
.tree {
  height: 200px;
  overflow-y: scroll;
}
.el-table .el-form-item {
  margin-bottom: 0;
}
</style>